package net.acoinWork.dynRender.configParse;

import net.acoinWork.dynRender.configParse.propertyModel.Common;
import net.acoinWork.dynRender.configParse.xmlModel.Command;
import net.acoinWork.dynRender.configParse.xmlModel.CommandCol;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * xml配置解析器,解析xml为java的pojo对象
 *
 * @author xusk
 * @since 15/12/31 上午9:50
 */
public final class ModelBuilder {
    private static final String WORK_PROPERTIES = "/ACoinWork.properties";
    private static final Properties defaultSetting = new Properties() {{
        this.setProperty("doDebug", "false");
        this.setProperty("libPath", "");
    }};
    private static final Common common;
    private static Properties properties;
    private final CommandCol commandCol = new CommandCol();//顶级pojo对象
    private final Map<String, Command> id2CmdMapping = new HashMap<String, Command>();
    private final SAXBuilder saxBuilder = new SAXBuilder();
    private Namespace nameSpace;//配置文件的命名空间
    private String xmlPath;//配置文件的位置

    static {
        //load properties
        properties = new Properties();
        try {
            properties.load(ModelBuilder.class.getResourceAsStream(WORK_PROPERTIES));
        } catch (IOException e) {
            System.out.println("no ACoinWork.properties was found in classpath, use default setting now..");
            properties = defaultSetting;
        }
        //parse properties to propertyModel
        common = new Common();
        for (Map.Entry<Object, Object> en : properties.entrySet()) {
            common.deliver((String) en.getKey(), (String) en.getValue());
        }
    }

    public ModelBuilder(String xmlPath, String nameSpace) throws JDOMException, IOException {
        this.xmlPath = xmlPath;
        this.nameSpace = Namespace.getNamespace(nameSpace);
    }

    /**
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public CommandCol buildXmlModel() throws JDOMException, IOException {
        Document document = saxBuilder.build(ModelBuilder.class.getResourceAsStream(xmlPath));
        Element root = document.getRootElement();
        commandCol.assemble(root, nameSpace);//最少知识原则
        for (Command cmd : commandCol.getCommands()) {
            id2CmdMapping.put(cmd.getId(), cmd);
        }
        return commandCol;
    }

    /**
     * 产生以xml中cmd-collection.cmd[id]为键,cmd-collection.cmd为key的map方便调用时快速查找
     *
     * @return
     */
    public Map<String, Command> getId2CmdMapping() {
        return Collections.unmodifiableMap(id2CmdMapping);
    }

    public static Common getCommon() {
        return common;
    }
}
